<script setup lang="jsx">
  import {watch,inject,ref,nextTick,reactive,computed,provide} from 'vue'
import waybillCar from '@/api/abroad/waybillCar'
import waybillTrayList from '@/api/abroad/waybillTrayList'
import { Message, Modal } from '@arco-design/web-vue'
import dicthelpApi from "@/api/dicthelpApi.js";
import {getDictData} from "@/utils/crud/dictNew.js";
import uploadConfig from '@/config/upload'
import tool from '@/utils/tool'
import ButtonGroup from "@cps/actionsNew/buttonGroup.vue";
const crudRef = ref()
const selected=ref([])

const columnsDist = inject('columnsDist')
// const crudFormShow=ref(false)
const span=ref(8)
const formRef=ref(null)
//table 选择
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  checkStrictly: true
});
// 表单数据
const rules = {
      type: [{ required: true, message:'请选择类型',validateTrigger: 'blur'}, ],
      tray_count: [{ required: true, message:'请输入可装托盘数',validateTrigger: 'blur'}, ],
    }
const trayList=ref([])
const shipmentList=ref([])
const formData = ref({
  id:'',
  type:'',
  carrier:'',
  car_number: null, 
  destination: null, 
  tray_count: null, 
  eta: null, 
  gta: null, 
  status:null,
})
//行数选中
const setSelecteds = (key) => {
  selected.value = key
}
const columnsTask = ref([
{title: '状态', dataIndex: 'status',slotName: 'status',width:100,align:'center',hide:true,},
{title: '服务类型', dataIndex: 'type',slotName: 'type',width:70,align:'center',hide:true,},
{title: '目的地', dataIndex: 'address',slotName: 'address',width:70,align:'center',hide:true,},
{title: '标题', dataIndex: 'title',width:100,hide:true,},
{title: '备注', dataIndex: 'remark',width:100,hide:true,},
{title: '创建日期', dataIndex: 'created_at',width:150,align:'center',hide:true,},
])
const columnsTray = ref([
  {title: '柜号', dataIndex: 'container_no',slotName: 'container_no',width:100,hide:true,},
  {title: '计费托盘数', dataIndex: 'tray_count_actual',width:180,align:'center',hide:true,},
  {title: '目的地', dataIndex: 'address_desc',slotName: 'address_desc',width:70,align:'center',hide:true,},
  {title: '箱数', dataIndex: 'parcel_count_actual',width:70,hide:true,},
])
const columnsTrayList = ref([
  {title: '托盘编号', dataIndex: 'number',width:70,hide:true,},
  {title: '提单号/入仓号', dataIndex: 'tray.order.number',width:180,align:'center',hide:true,},
  {title: '柜号', dataIndex: 'tray.order.container_no',width:70,hide:true,},
{title: '目的地', dataIndex: 'address_desc',slotName: 'address_desc',width:70,align:'center',hide:true,},
  {title: '服务类型', dataIndex: 'service_type_id',slotName: 'service_type_id',width:150,align:'center',hide:true,},
  {title: 'ETA/入仓时间', dataIndex: 'tray.unpacking_at',width:150,align:'center',hide:true,},
  // {title: '操作', slotName: 'fixed',fixed: 'right',width: 70,align:'center',},


])
const columnsShipment = ref([  
  {title: '入库日期', dataIndex: 'shipment.unpacking_at',width:150,align:'center',hide:true,},
  {title: '服务类型', dataIndex: 'service_type_id',slotName: 'service_type_id',width:150,align:'center',hide:true,},
{title: '目的地', dataIndex: 'address_desc',slotName: 'address_desc',width:70,align:'center',hide:true,},
  {title: '箱唛', dataIndex: 'shipment.shipment_no',width:100,align:'center',hide:true,},
  {title: '柜号', dataIndex: 'shipment.container_no',width:100,align:'center',hide:true,},
  {title: '箱数', dataIndex: 'count',width:100,align:'center',hide:true,},
  {title: '入库重量', dataIndex: 'shipment.weight',width:100,align:'center',hide:true,},
  {title: '库存CBM', dataIndex: 'shipment.volume',width:100,align:'center',hide:true,},
  {title: '库龄/天', dataIndex: 'shipment.age',width:100,align:'center',hide:true,},
  // {title: '操作', slotName: 'fixed',fixed: 'right',width: 70,align:'center',},
]);
//下载
const downloadTap=(item)=>{
  let url=uploadConfig.storage.OSS+item.filepath
  window.location.href=url
}
 //详情
 const infoGet=()=>{
  waybillCar.read(formData.value.id).then(res => {
        formData.value=res.data
        formData.value.type=res.data.type.toString()
        formData.value.tray_count=res.data.tray_count.toString()
        waybillListCarData()
        waybillTrayListCarData()
      }) 
    }
     //运单
    const waybillListCarData=()=>{
      waybillCar.waybillListCar({ scence:'shipment',car_id:formData.value.id,page: 1,pageSize: 100, }).then(res => {
        shipmentList.value=res.data.items
        })
    }
     //托盘
    const waybillTrayListCarData=()=>{
      waybillCar.waybillTrayListCar({ scence:'list',car_id:formData.value.id,page: 1,pageSize: 100, }).then(res => {
        trayList.value=res.data.items

      })
    }
   
const visible = ref(false)
  const onShow = async (value) => {
    visible.value = true
     //编辑
     if(value){
      formData.value.id=value.id
      infoGet()
    }
    
  }

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
//   open: false,
  // 弹出层标题（用户导入）
  title: "",
  fileList:[],
  // 是否禁用上传
  isUploading: false,
  data:{
    image:''
  },
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + tool.getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_URL + "/system/uploadImage"
});

const emits = defineEmits(['addClick','emitClick'])
  //新增 //编辑
  const handleBeforeOk =async (formEl) => {
      let formParse = JSON.parse(JSON.stringify(formData.value)); // 深拷贝数据
      // console.log(' upload.fileList', upload.fileList)
      // upload.fileList.map((item,index)=>{
      //     if(item.response?.data?.hash){
      //       formParse.file=item.response?.data?.hash
      //     }
      //   })
    if (!formEl) return
      await formEl.validate((valid) => {
        if (!valid) {
          if(formParse.id==''){
            waybillCar.save(formParse).then(res => {
              Message.success(res.message || `新增成功！`)
              emits('addClick');
              close()
            })
          }else{
            waybillCar.update(formParse).then(res => {
              Message.success(res.message || `编辑成功！`)
              emits('addClick');
              close()
            })
          }
          
        }
      }) 
      
    };

    const close = () => {
      formRef.value.resetFields();
      visible.value = false
      formData.value.id=''
      trayList.value=[]
      shipmentList.value=[]
      selected.value=[]
    }
const onBeforeCancel=()=>{
  Modal.confirm({
        title: '确认关闭?',
        onOk: () => {
          close()
        },
      });
}
const buttonGroups = [
{
    title: '解除关系',
    api:waybillCar.outCar,
    auth: ['sea:waybillCar:outCar'],
    addType:2,
    hideStatus: [],
  }
]
provide('infoGet',infoGet);

defineExpose({ onShow })
</script>

<template>
  <a-drawer v-model:visible="visible" v-if="visible" width="80%" :onBeforeCancel="onBeforeCancel">
        <template #title>
          <div >{{  formData.id == "" ? '新增' : '编辑'}}</div>
          </template>
          <a-form ref="formRef" :rules="rules" :model="formData">
            <div class="form-top-main">
              <a-col :span="span">
              <a-form-item field="type" label="类型" validate-trigger="change">
                <a-select v-model="formData.type"  :options="columnsDist.dictObj.data.waybill_sea_car_type" :field-names="{ value: 'key', label: 'title' }"
                    placeholder="请选择类型" style="width: 400px;" allow-search :virtual-list-props="{height:200}" /> 
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="car_number" label="车牌号" validate-trigger="change">
                <a-input v-model="formData.car_number"  placeholder="请输入车牌号" />
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="carrier" label="承运商" validate-trigger="change">
                <a-select v-model="formData.carrier" :options="columnsDist.dicthelpApi_supplier.data"
                          :field-names="{ value: 'id', label: 'name' }"
                          placeholder="请选择承运商" allow-clear allow-search :virtual-list-props="{height:200}"/>
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="destination" label="目的地" validate-trigger="change">
                <a-input v-model="formData.destination"  placeholder="请输入目的地" />
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="tray_count" label="可装托盘数" validate-trigger="change">
                <a-input v-model="formData.tray_count"  placeholder="请输可装托盘数" />
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="eta" label="预计送达时间" validate-trigger="change">
                <a-date-picker
                  style="width: 100%;"
                  placeholder="预计送达时间"
                  v-model="formData.eta"
                />
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="gta" label="送达时间" validate-trigger="change">
                <a-date-picker
                  style="width: 100%;"
                  :disabled="formData.status<3"
                  placeholder="送达时间"
                  v-model="formData.gta"
                />
              </a-form-item>
            </a-col>
            <!-- <a-col :span="span">
              <a-form-item field="file" label="图片" validate-trigger="change">
                <a-upload style="margin-top: 10px;" name="image" accept=".jpg,.jpeg,.png"  v-model:file-list="upload.fileList" :action="upload.url" :headers="upload.headers" />
              </a-form-item>
            </a-col> -->

          </div>
          <a-tabs default-active-key="1" v-if="formData.id!=''">
            <a-tab-pane key="1" title="出库单">
              <div style="display: flex;margin: 10px 0;" v-if="formData?.task!=''">
                <button-group :button-groups="buttonGroups" :dataList="formData.task" :crud-ref="crudRef" :selected="selected"
                              />
              </div>
              <a-table ref="taskTableRef"  row-key="id" :columns="columnsTask" :data="formData.task" :bordered="false"  size="mini"
              v-model:selectedKeys="selected" @selection-change="setSelecteds($event)" stripe :row-selection="rowSelection" column-resizable :pagination="false">
                <template #status="{ record }">{{getDictData('dictObj','waybill_sea_task_send_status',record.status,2,columnsDist) }}</template> 
                <template #type="{ record }">{{getDictData('attrApi','dicthelpApi_waybillServiceShipmentTypeList',record.type,3,columnsDist) }}</template>
                <template #address="{ record }">{{getDictData('attrApi','dicthelpApi_addressChang',record.address,1,columnsDist) }}</template>
              </a-table>
            </a-tab-pane>
            <a-tab-pane key="2" title="托盘组">
           
              <a-table ref="trayTableRef"  row-key="id" :columns="columnsTray" :data="formData.tray" :bordered="false"  size="mini" column-resizable :pagination="false">
                <template #container_no="{ record }">
                  {{record.order.container_no}}
                </template> 
                <template #address_desc="{ record }">{{record?.address_desc}}</template>

                  <template #fixed="{ record,rowIndex }">
                    <a-link title="删除" @click="deleteAction(rowIndex,1)"><icon-delete /></a-link>                      
                  </template>
              </a-table>
            </a-tab-pane>
            <a-tab-pane key="3" title="托盘">
              <a-table ref="trayListTableRef"  row-key="number" :columns="columnsTrayList" :data="trayList" :bordered="false"  size="mini" column-resizable :pagination="false">
                  <template #service_type_id="{ record }">{{getDictData('attrApi','dicthelpApi_waybillServiceShipmentTypeList',record.tray.service_type_id,3,columnsDist) }}</template>
                  <template #address_desc="{ record }">{{record.tray?.address_desc}}</template>

              </a-table>
            </a-tab-pane>
            <a-tab-pane key="4" title="运单">
          
              <a-table ref="shipmentTableRef"  row-key="shipment_id" :columns="columnsShipment" :data="shipmentList" :bordered="false"  size="mini" column-resizable :pagination="false">
                  <template #service_type_id="{ record }">{{getDictData('attrApi','dicthelpApi_waybillServiceShipmentTypeList',record.tray.service_type_id,3,columnsDist) }}</template>
                <template #address_desc="{ record }">{{record.tray?.address_desc}}</template>
              </a-table>
            </a-tab-pane>
            <a-tab-pane key="5" title="附件">
              <div>
                <div v-for="item in formData.files" :key="item.about_id" style="display: flex;margin-top: 10px;justify-content: space-between;padding: 0 10px;background: #ddd;">
                  <div>{{item.filename}}</div>
                  <div>类型：{{getDictData('dictObj','AttachmentType',item.attachable_type,2,columnsDist) }}</div>
                  <div>上传时间：{{item.created_at}}</div>
                  <a-link  title="下载" @click="downloadTap(item)"><icon-to-bottom /></a-link>
                </div>
              </div>
            </a-tab-pane>
            </a-tabs>
        </a-form>
        <template #footer> 
          <div style="display: flex; justify-content: space-between;align-items: center;">
            <div style="color: rgb(50 193 148);">
              <!-- tips：先选择"服务项目"后在操作明细,请按要求填写(导入)单据信息 -->
            </div>
            <div>
              <a-button @click="visible = false" style="margin-right: 20px;">关闭</a-button>
              <a-button type="primary" @click="handleBeforeOk(formRef)">
                保存
              </a-button>
            </div>
          </div>       
        </template>
      </a-drawer>
</template>
<style>
   .form-top-main{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    width: 100%;
   }
   .tab-main{
    display: flex;
    align-items: center;
    margin: 10px 0;
   }
   .tab-main .arco-form-item{
    margin-bottom: 0;
   }
   .tab-main .arco-switch{
    margin-right: 20px;
   }
</style>